#include "../include/head.h"

// 管理员添加商品
void add_func(CommodityList *list)
{
    Commodity commodity;
    system("clear");
    printf(BOLD("▷ 请输入商品编号(编号唯一): "));
    scanf("%s", commodity.id);
    // 检查商品编号是否已存在
    CommodityNode *current = list->head;
    while (current != NULL)
    {
        if (strcmp(current->commodity.id, commodity.id) == 0)
        {
            printf(RED("商品编号已存在，请重新添加。")"\n");
            return;
        }
        current = current->next;
    }
    printf(BOLD("▷ 请输入商品名称: "));
    scanf("%s", commodity.name);
    printf(BOLD("▷ 请输入商品价格: "));
    //检查价格是否为数字
    while (1)
    {
        char price_str[20];
        scanf("%s", price_str);
        if (sscanf(price_str, "%f", &commodity.price) == 1)
        {
            // 检查价格是否为正数
            if (commodity.price > 0)
            {
                break;
            }
            else
            {
                printf(RED("请输入有效的商品价格: "));
            }
        }
        else
        {
            printf(RED("请输入有效的商品价格: "));
        }
    }
    printf(BOLD("▷ 请输入商品库存: "));
    //检查库存是否为数字
    while (1)
    {
        char stock_str[20];
        scanf("%s", stock_str);
        if (sscanf(stock_str, "%d", &commodity.stock) == 1)
        {
            // 检查库存是否为正数
            if (commodity.stock >= 0)
            {
                break;
            }
            else
            {
                printf(RED("请输入有效的商品库存: ") "\n");
            }
        }
        else
        {
            printf(RED("请输入有效的商品库存: ") "\n");
        }
    }
    // 添加商品信息到链表
    add_commodity(list, commodity);
    // 将商品信息写入文件
    write_commodity_to_file(list);

    //打印显示给用户
    print_table_header();
    current = list->head;
    print_custom_table(current);
    print_table_tail();
    printf(GREEN("商品添加成功！")"\n");
    
}

/*=====================================================================================================================================*/

// 显示所有商品信息
void display_commodities(CommodityList *list) {
    
    //打印表头函数
    print_table_header();
    

    CommodityNode *current = list->head;
    while (current != NULL) {
        print_custom_table(current);
        if(current->next != NULL)
        {
            printf("\033[1;36m├────────────┼────────────────┼────────────┼────────────┤\033[0m\n");
        }
        
        current = current->next;
    }
    
    print_table_tail();
}

/*=====================================================================================================================================*/

// 管理员商品信息查删改（可根据商品编号、名称等关键字进行查询,查询后询问是否删除或修改）
void search_func(CommodityList *list) {
    system("clear");
    
    // 打印查询标题
    printf("\033[1;36m┌──────────────────────────────────────┐\n");
    printf("│          \033[1;33m🔍 商品查询系统\033[1;36m             │\n");
    printf("└──────────────────────────────────────┘\033[0m\n");
    
    // 获取查询关键字
    char keyword[20];
    printf("\033[1;37m▷ 请输入查询关键字: \033[0m");
    scanf("%s", keyword);

    
    //打印表头函数
    print_table_header();

    CommodityNode *current = list->head;
    int found = 0;
    while (current != NULL) {
        if (strstr(current->commodity.id, keyword) || 
            strstr(current->commodity.name, keyword)) 
        {
                print_custom_table(current);
                found++;
        }
        current = current->next;
    }
    
    // 表格底部边框
    print_table_tail();

    if (!found) {
        printf("\033[1;31m⚠ 未找到相关商品信息。\033[0m\n");
        return;
    }

    // 操作选项
    printf("\n\033[1;35m▷ 是否删除或修改商品？\033[0m\n");
    printf("\033[33m1. 🗑 删除商品\033[0m\n");
    printf("\033[34m2. ✏ 修改商品\033[0m\n");
    printf("\033[90m3. 返回主菜单\033[0m\n");
    printf("\033[1;37m▷ 请选择操作[1-3]: \033[0m");
    
    char choice;
    scanf(" %c", &choice);

    if (choice == '1') 
    { // 删除商品
        system("clear");
        printf("\033[1;33m🗑 删除商品\033[1;36m\n");
        //打印表头函数
        print_table_header();
        
        // 重新显示匹配商品
        current = list->head;
        while (current != NULL) {
            if (strstr(current->commodity.id, keyword) || 
                strstr(current->commodity.name, keyword)) 
            {
                   print_custom_table(current);
            }
            current = current->next;
        }
        print_table_tail();

        printf("\033[1;37m▷ 请输入要删除的商品编号: \033[0m");
        
        char delete_id[64];
        scanf("%s", delete_id);
        CommodityNode *prev = NULL; // 上一个节点
        current = list->head; 
        while (current != NULL)
        {
            if (strcmp(current->commodity.id, delete_id) == 0)
            {
                system("clear");
                //打印表头函数
                print_table_header();
                printf(CYAN("│ "));
                print_fixed_width2(current->commodity.id, ID_WIDTH-1);

                printf(CYAN("│ "));
                print_fixed_width2(current->commodity.name, NAME_WIDTH-1);
    
                printf(CYAN("│ "));
                char price_str[20];
                sprintf(price_str, "%.2f", current->commodity.price);
                print_fixed_width2(price_str, PRICE_WIDTH-1);
    
                printf(CYAN("│ "));
                char stock_str[20];
                sprintf(stock_str, "%d", current->commodity.stock);
                print_fixed_width2(stock_str, STOCK_WIDTH-1);
    
                printf(CYAN("│\n"));
                print_table_tail();

                if (prev == NULL)
                {
                    list->head = current->next;
                }
                else
                {
                    prev->next = current->next;
                }
                free(current);
                list->size--;
                printf("\033[1;37m商品删除成功\033[0m\n");
                break;
            }
            prev = current;// 更新上一个节点
            current = current->next;// 更新当前节点
        }
        if (current == NULL)
        {
            printf("\033[1;31m⚠ 未找到相关商品信息。\033[0m\n");
        }
        // 将商品信息写入文件
        write_commodity_to_file(list);
    } 
    else if (choice == '2') 
    { // 修改商品
        system("clear");
        system("clear");
        printf("\033[1;33m🗑 删除商品\033[1;36m\n");
        //打印表头函数
        print_table_header();
        
        // 重新显示匹配商品
        current = list->head;
        while (current != NULL) {
            if (strstr(current->commodity.id, keyword) || 
                strstr(current->commodity.name, keyword)) 
                {
                    print_custom_table(current);
                }
            current = current->next;
        }
        print_table_tail();

        printf("\033[1;37m▷ 请输入要修改的商品编号: \033[0m");
        char modify_id[64];
        scanf("%s", modify_id);
        CommodityNode *current = list->head;
        while (current != NULL)
        {
            if (strcmp(current->commodity.id, modify_id) == 0)
            {
                //将原数据存起来
                Commodity old_commodity = current->commodity;
                printf("\033[1;37m▷ 请输入新的商品名称: \033[0m");
                scanf("%s", current->commodity.name);
                printf("\033[1;37m▷请输入新的商品价格: \033[0m");
                scanf("%f", &current->commodity.price);
                printf("\033[1;37m▷请输入新的商品库存: \033[0m");
                scanf("%d", &current->commodity.stock);


                print_table_header();
                printf(CYAN("│ "));
                print_fixed_width(current->commodity.id, ID_WIDTH-1);
                printf(CYAN("│ "));

                //比较是否修改名称，如果修改了就调用绿色版本
                if (strcmp(old_commodity.name, current->commodity.name) != 0)
                {
                    print_fixed_width3(current->commodity.name, NAME_WIDTH-1);
                }
                else
                {
                    print_fixed_width(current->commodity.name, NAME_WIDTH-1);
                }
                printf(CYAN("│ "));


                //比较价格是否修改，如果修改了就调用绿色版本
                char price_str[20];
                sprintf(price_str, "%.2f", current->commodity.price);
                if (old_commodity.price != current->commodity.price)
                {
                    print_fixed_width3(price_str, PRICE_WIDTH-1);
                }
                else
                {
                    print_fixed_width(price_str, PRICE_WIDTH-1);
                }
                printf(CYAN("│ "));


                //比较库存是否修改，如果修改了就调用绿色版本
                char stock_str[20];
                sprintf(stock_str, "%d", current->commodity.stock);
                if (old_commodity.stock != current->commodity.stock)
                {
                    print_fixed_width3(stock_str, STOCK_WIDTH-1);
                }
                else
                {
                    print_fixed_width(stock_str, STOCK_WIDTH-1);
                }

                printf(CYAN("│\n"));
                print_table_tail();

                printf(GREEN("商品修改成功！")"\n");
                break;
            }
            current = current->next;
        }
        if (current == NULL)
        {
            printf("\033[1;31m⚠ 未找到相关商品信息。\033[0m\n");
        }
        // 将商品信息写入文件
        write_commodity_to_file(list);
    }else {
        printf("\033[90m↩ 操作已取消，返回主菜单...\033[0m\n");
    }
}

/*=====================================================================================================================================*/

//用户查询商品
void user_search_func(CommodityList *list , CommodityList *shopping_cart)
{
    system("clear");
    
    // 打印查询标题
    printf("\033[1;36m┌──────────────────────────────────────┐\n");
    printf("│          \033[1;33m🔍 商品查询系统\033[1;36m             │\n");
    printf("└──────────────────────────────────────┘\033[0m\n");
    
    // 获取查询关键字
    char keyword[20];
    printf("\033[1;37m▷ 请输入查询关键字: \033[0m");
    scanf("%s", keyword);

    
    //打印表头函数
    print_table_header();

    CommodityNode *current = list->head;
    int found = 0;
    while (current != NULL) {
        if (strstr(current->commodity.id, keyword) || 
            strstr(current->commodity.name, keyword)) {
                print_custom_table(current);
                found++;
        }
        current = current->next;
    }
    
    // 表格底部边框
    print_table_tail();

    if (!found) {
        printf("\033[1;31m⚠ 未找到相关商品信息。\033[0m\n");
        return;
    }
    printf("\033[1;37m▷ 是否添加商品到购物车？\033[0m\n\n");
    printf("\033[33m1. ✅ 添加商品到购物车\033[0m\n");
    printf("\033[90m2. ❌ 返回主菜单\033[0m\n\n");
    printf("\033[1;37m▷ 请选择操作[1-2]: \033[0m");
    char choice;
    scanf(" %c", &choice);
    if (choice == '1') 
    { // 添加到购物车
        system("clear");
        printf("\033[1;33m✅ 添加到购物车\033[1;36m\n");
        //打印表头函数
        print_table_header();
        
        // 重新显示匹配商品
        current = list->head;
        while (current != NULL) {
            if (strstr(current->commodity.id, keyword) || 
                strstr(current->commodity.name, keyword)) 
                {
                    print_custom_table(current);
                }
            current = current->next;
        }
        print_table_tail();
    } 
    else {
        printf("\033[90m↩ 操作已取消，返回主菜单...\033[0m\n");
        return;
    }
    printf("\033[1;37m▷ 请输入要添加到购物车的商品编号: \033[0m");
    char add_id[64];
    scanf("%s", add_id);
    printf("\033[1;37m▷ 请输入要添加到购物车的商品数量: \033[0m");
    int add_quantity;
    //检查数量是否为数字
    while (1)
    {
        char quantity_str[20];
        scanf("%s", quantity_str);
        if (sscanf(quantity_str, "%d", &add_quantity) == 1)
        {
            // 检查数量是否为正数
            if (add_quantity > 0)
            {
                break;
            }
            else
            {
                printf(RED("请输入有效的商品数量: ") "\n");
            }
        }
        else
        {
            printf(RED("请输入有效的商品数量: ") "\n");
        }
    }
    CommodityNode *current2 = list->head;
    CommodityNode *new_node = shopping_cart->head;
    while (new_node != NULL)
    {
        if (strcmp(new_node->commodity.id, add_id) == 0)
        {
            printf("\033[1;31m⚠ 商品已在购物车中,请勿重复添加。\033[0m\n");
            return;
        }
        new_node = new_node->next;
    }

    while (current2 != NULL)
    {
        if (strcmp(current2->commodity.id, add_id) == 0)
        {
            if (add_quantity > current2->commodity.stock)
            {
                printf("\033[1;31m⚠ 库存不足，添加失败。\033[0m\n");
                return;
            }
            else
            {
                //将商品添加到购物车链表
                CommodityNode *new_node = (CommodityNode *)malloc(sizeof(CommodityNode));
                if (new_node == NULL)
                {
                    perror("无法分配内存");
                    exit(EXIT_FAILURE);
                }
                new_node->commodity = current2->commodity;
                new_node->commodity.stock = add_quantity;
                new_node->next = shopping_cart->head;
                shopping_cart->head = new_node;
                shopping_cart->size++;
  
                printf(GREEN("商品添加到购物车成功！")"\n");
                break;
            }
        }
        current2 = current2->next;
    }
    if (current2 == NULL)
    {
        printf("\033[1;31m⚠ 未找到相关商品信息。\033[0m\n");
    }
    // 将商品信息写入文件
    write_shopping_cart_to_file(shopping_cart);

}

/*=====================================================================================================================================*/

//商品库存出入
void stock_in_out_func(CommodityList *list)
{
    //显示所有商品
    display_commodities(list);
    char id[64];
    int old_stock;
    int quantity;
    printf("\033[1;37m▷ 请输入要出入库的商品编号: \033[0m");
    scanf("%s", id);
    printf("\033[1;37m▷ 请输入出入库存的数量(正数为入库，负数为出库): \033[0m");
    scanf("%d", &quantity);

    CommodityNode *current = list->head;
    while (current != NULL)
    {
        if (strcmp(current->commodity.id, id) == 0)
        {
            old_stock = current->commodity.stock;
            current->commodity.stock += quantity;
            printf("\033[1;37m 库存更新成功！\033[0m\n");

            if (quantity > 0)
            {
                printf("商品库存: "RED("%d")"->"GREEN("%d")"\n",old_stock ,current->commodity.stock);
                print_table_header();
                print_custom_table(current);
                print_table_tail();
            }
            else
            {
                printf("商品库存: "GREEN("%d")"->"RED("%d")"\n",old_stock ,current->commodity.stock);
                print_table_header();
                print_custom_table(current);
                print_table_tail();
            }
            
            break;
        }
        current = current->next;
    }
    if (current == NULL)
    {
        printf("\033[1;31m⚠ 未找到相关商品信息。\033[0m\n");
    }
    // 将商品信息写入文件
    write_commodity_to_file(list);
}

/*=====================================================================================================================================*/

//商品排序
void sort_commodities(CommodityList *list)
{
    int sort_type;
    printf("\033[1;36m┌──────────────────────────────────────┐\n");
    printf("│          \033[1;33m🔄 商品排序方式\033[1;36m             │\n");
    printf("├──────────────────────────────────────┤\n");
    
    // 排序选项（带图标和颜色）
    printf("│\033[0m  \033[32m1. ↑ 价格升序\033[0m                       \033[1;36m│\n");
    printf("│\033[0m  \033[31m2. ↓ 价格降序\033[0m                       \033[1;36m│\n");
    printf("│\033[0m  \033[34m3. ↑ 编号升序\033[0m                       \033[1;36m│\n");
    printf("│\033[0m  \033[35m4. ↓ 编号降序\033[0m                       \033[1;36m│\n");
    printf("└──────────────────────────────────────┘\033[0m\n\n");
    
    // 输入提示（带闪烁光标）
    printf("\033[5;37m▷ 请选择排序方式 [1-4]: \033[0m");
    scanf("%d", &sort_type);
    if (sort_type != 1 && sort_type != 2 && sort_type != 3 && sort_type != 4)
    {
        printf("\033[1;31m⚠ 无效的排序方式！\033[0m\n");
        return;
    }
    CommodityNode *current, *next;
    for (current = list->head; current != NULL; current = current->next)
    {
        for (next = current->next; next != NULL; next = next->next)
        {
            if ((sort_type == 1 && current->commodity.price > next->commodity.price) || // 升序
                (sort_type == 2 && current->commodity.price < next->commodity.price))   // 降序
            {
                Commodity temp = current->commodity;
                current->commodity = next->commodity;
                next->commodity = temp;
            }
            else if ((sort_type == 3 && strcmp(current->commodity.id, next->commodity.id) > 0) || // 升序
                     (sort_type == 4 && strcmp(current->commodity.id, next->commodity.id) < 0))   // 降序
            {
                Commodity temp = current->commodity;
                current->commodity = next->commodity;
                next->commodity = temp;
            }
        }
    }
    system("clear");
    // 显示排序后的商品信息
    display_commodities(list);
    // 将商品信息写入文件
    write_commodity_to_file(list);
    printf("商品排序成功！\n");
}

/*=====================================================================================================================================*/

